<?php
declare(strict_types=1);

namespace App\System\Service;

use App\System\Utils\Tree;
use Haozing\FastCore\Abstract\AbstractService;
use App\System\Service\Interface\IHeiTenantMenuService;
use App\System\Service\Model\HeiTenantMenu;
use Haozing\FastCore\Model\Model;
use Hyperf\Di\Annotation\Inject;

class HeiTenantMenuService extends AbstractService implements IHeiTenantMenuService
{
    #[Inject]
    protected HeiMenuService $menuService;

    /**
     * @return void
     */
    function setModel(): void
    {
        $this->model = \Hyperf\Support\make(HeiTenantMenu::class);
    }
    public function getModel(): Model
    {
       return $this->model;
    }

    /**
     * 获取租户管理员菜单
     */
    public function getTenantAdminMenu(): array
    {
        // 获取租户所有的菜单id
        $menuIds = $this->getOneByWhere([],['menu_id']);
        $menuIds = $menuIds['menu_id']??'*';
        //如果menuIds为空,或者是*则表示所有菜单
        $menuIds = $menuIds == '*' ? $menuIds : explode(',',$menuIds);
        //查询菜单
        $where = [
            ['status','=',1]
        ];
        if ($menuIds != '*') {
            $where = ['id', 'in', $menuIds];
        }
        return $this->menuService->getManyByWhere($where,['*'],['orderByRaw'=> 'sort desc']);
    }
    /**
     * 根据id获取租户管理员菜单
     */
    public function getTenantAdminMenuById(array $ids): array
    {
        $menus = $this->getTenantAdminMenu();
        return $this->menuToRouterTree($menus);
    }
    /**
     * 获取租户管理员菜单路由树.
     */
    public function getTenantAdminRouterTree(): array
    {
        $menus = $this->getTenantAdminMenu();
        return $this->menuToRouterTree($menus);
    }
    /**
     * 系统菜单转前端路由树.
     */
    public function menuToRouterTree(array $data): array
    {
        if (empty($data)) {
            return [];
        }

        $routers = [];
        foreach ($data as $menu) {
            array_push($routers, $this->setRouter($menu));
        }
        return Tree::toTree($routers);
    }

    public function setRouter(&$menu): array
    {
        $route = ($menu['type'] == 'L' || $menu['type'] == 'I') ? $menu['route'] : '/' . $menu['route'];
        return [
            'id' => $menu['id'],
            'parent_id' => $menu['parent_id'],
            'name' => $menu['code'],
            'component' => $menu['component'],
            'path' => $route,
            'redirect' => $menu['redirect'],
            'meta' => [
                'type' => $menu['type'],
                'icon' => $menu['icon'],
                'title' => $menu['name'],
                'hidden' => ($menu['is_hidden'] === 1),
                'hiddenBreadcrumb' => false,
            ],
        ];
    }
}